package com.ikun.yummy.activitys.setting;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.text.InputType;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.ikun.yummy.App;
import com.ikun.yummy.R;
import com.ikun.yummy.bean.UserInfo;
import com.ikun.yummy.manager.UserOpManager;
import com.ikun.yummy.sourceop.op.UserOP;
import com.ikun.yummy.utils.CommonUtils;
import com.ikun.yummy.utils.ReadImageUtil;

import java.io.File;
import java.nio.file.Files;

public class SettingActivity extends AppCompatActivity {
    private static final int IMAGE_REQUEST_CODE = 10;
    private ArrayAdapter adp;
    private String[] data={"我的账号","修改密码","通用设置","通知设置","功能申请","帮助or客服","关于","退出登录"};
    private ImageView img;
    UserOpManager userOpManager;
    @SuppressLint("WrongConstant")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);//左侧添加一个默认的返回图标
        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用

        ListView list = findViewById(R.id.account_list);
        img=findViewById(R.id.setting_img);
        userOpManager=new UserOpManager(this);
        File des=new File(userOpManager.queryUser(App.sp.getString("username","null")).userimage);
        if (des.exists()){
            img.setImageBitmap(BitmapFactory.decodeFile(des.getAbsolutePath()));
        }
        adp= new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, data);
        list.setAdapter(adp);
        list.setOnItemClickListener((parent, view, position, id) -> {
            if (data[position].equals("修改密码")){
                EditText oldPsw=new EditText(this);
                oldPsw.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PASSWORD);
                oldPsw.setHint("请输入原密码");
                EditText newPsw=new EditText(this);
                newPsw.setHint("请输入新密码");
                newPsw.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PASSWORD);
                EditText newPsw2=new EditText(this);
                newPsw2.setHint("请再次输入新密码");
                newPsw2.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PASSWORD);
                LinearLayout v=new LinearLayout(this);
                v.setOrientation(1);
                v.addView(oldPsw);
                v.addView(newPsw);
                v.addView(newPsw2);
                AlertDialog.Builder dialog=new AlertDialog.Builder(this);
                dialog.setTitle("修改密码").setView(v).setPositiveButton("确定", (dialog1, which) -> {
                    if (!oldPsw.getText().toString().equals("")&&!newPsw.getText().toString().equals("")&&!newPsw2.getText().toString().equals("")){
                        if (newPsw.getText().toString().equals(newPsw2.getText().toString())){
                            userOpManager=new UserOpManager(this);
                            userOpManager.update(new UserInfo(App.sp.getString("username","null"),newPsw.getText().toString(),"1",null,null));
                            Toast.makeText(this,"修改完成",Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(this,"两次密码不一样",Toast.LENGTH_SHORT).show();
                        }
                    }else {
                        Toast.makeText(this,"请输入完整",Toast.LENGTH_SHORT).show();
                    }
                }).setNegativeButton("取消",null).show();
            }
            if (data[position].equals("退出登录")){
                UserOpManager userOpManager=new UserOpManager(this);
                userOpManager.update(new UserInfo(App.sp.getString("username","null"),null,"0",null,null));
                finish();
            }
        });
        UserOP userOP =new UserOP(this);
        UserInfo userInfo = userOP.queryUserByUsername(App.sp.getString("username","null"));
        data[0]="我的账号:"+ userInfo.username;
        adp.notifyDataSetChanged();
    }
    public void changeImg(View view) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission. WRITE_EXTERNAL_STORAGE }, 1);
        }else {
            Intent intent = new Intent("android.intent.action.GET_CONTENT");
            intent.setType("image/*");
            startActivityForResult(intent, IMAGE_REQUEST_CODE);
        }
    }
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==IMAGE_REQUEST_CODE){
            if (resultCode == RESULT_OK) { // 判断手机系统版本号
                ReadImageUtil readImageUtil = new ReadImageUtil();
                String path;
                if (Build.VERSION.SDK_INT >= 19) { path = readImageUtil.handleImageOnKitKat(this,data); } else { path = readImageUtil.handleImageBeforeKitKat(this,data);}
                File des=new File(CommonUtils.getPath(this) +"/myIcon_"+System.currentTimeMillis()+".jpg");
                File old=new File(userOpManager.queryUser(App.sp.getString("username","null")).userimage);
                if (old.exists()){
                    old.delete();
                }
                String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE };
                int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                if (permission != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, 1);
                }
                try {
                    Files.copy(new File(path).toPath(),des.toPath());
                    //复制一下
                    userOpManager.update(new UserInfo(App.sp.getString("username","null"),null,"1",des.getAbsolutePath(),null));
                    img.setImageBitmap(BitmapFactory.decodeFile(des.getAbsolutePath()));
                    Toast.makeText(this,"头像更换成功",Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(this,"头像更换失败",Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (android.R.id.home==item.getItemId()){
            finish();
        }
        return super.onOptionsItemSelected(item);
    }
}
